'''
Created on 2011-3-4

@author: bnw
'''
import urllib2
from BeautifulSoup import BeautifulSoup, Tag
import re
from stocktable import stocklist

if __name__ == '__main__':
    
    for stock in stocklist:
        stockid = stock[0]

##        if stockid != '000401':
##            continue
        
        print stockid
        
        urlstr = "http://money.finance.sina.com.cn/corp/go.php/vFD_FinanceSummary/stockid/" + stockid + ".phtml"
        page = urllib2.urlopen(urlstr)
        soup = BeautifulSoup(page)
        fpathstr = "F:/data/FinanceSummary/" + stockid + ".txt"
        f = open(fpathstr, 'w')
        table = soup('table', id = 'FundHoldSharesTable')[0]
        trs = table('tr')[1:]
        time = ''
        data1 = ''
        data2 = ''
        data3 = ''
        data4 = ''
        for i in range(len(trs)):
            if i%14 == 0:
                time = trs[i]('td')[1].strong.string
            elif i%14 == 2:
                if trs[i]('td')[1].a != None:
                    data = trs[i]('td')[1].a.string
                else:
                    data = trs[i]('td')[1].string
                data1 = data[:len(data)-1]
            elif i%14 == 3:
                if trs[i]('td')[1].a != None:                   
                    data = trs[i]('td')[1].a.string
                else:
                    data = trs[i]('td')[1].string
                data2 = data[:len(data)-1]
            elif i%14 == 4:
                if trs[i]('td')[1].a != None: 
                    data = trs[i]('td')[1].a.string
                else:
                    data = trs[i]('td')[1].string
                data3 = data[:len(data)-1]
            elif i%14 == 5:
                if trs[i]('td')[1].a != None: 
                    data = trs[i]('td')[1].a.string
                else:
                    data = trs[i]('td')[1].string
                data4 = data[:len(data)-1]
                f.write(time)
                f.write('\t')
                f.write(data1)
                f.write('\t')
                f.write(data2)
                f.write('\t')
                f.write(data3)
                f.write('\t')
                f.write(data4)
                f.write('\n')
            else:
                continue
        f.close()    
        
    
